<template>
	<!-- 新建差旅报销单  -->
	<view class="container"
		style="width: 100%;box-sizing: border-box;background-color: #fff;padding:20rpx 20rpx 20rpx 20rpx">
		<uni-forms ref="form" :modelValue="entity" label-width="130px">
			<view>
				<view>
					<uni-section title="基本信息" type="line"></uni-section>
				</view>
				<uni-forms-item label="报销单号:" name="ReimburseCode">
					<view>
						<uni-easyinput v-model="entity.ReimburseCode" :disabled="true" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="报销单名称:" name="ReimburseName">
					<view>
						<uni-easyinput v-model="entity.ReimburseName" :disabled="disabled" />
					</view>
				</uni-forms-item>

				<uni-forms-item label="申请日期:" :rules="$rules.handle.ApplicationDate" required name="ApplicationDate">
					<view @click="DateChange($event, 'ApplicationDate')">
						<uni-easyinput v-model="entity.ApplicationDate" :disabled="true" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="公司名称:" :rules="$rules.handle.CompanyName" required name="CompanyName">
					<view @click="CustomerChoice('CompanyName')">
						<uni-easyinput v-model="entity.CompanyName" suffixIcon="compose" :disabled="disabled" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="部门名称:" :rules="$rules.handle.DeptName" required name="DeptName">
					<view @click="CustomerChoice('DeptName')">
						<uni-easyinput v-model="entity.DeptName" suffixIcon="compose" :disabled="disabledDeptName" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="报销人姓名:" :rules="$rules.handle.ApplicationPerson" required
					name="ApplicationPerson">
					<view>
						<uni-easyinput v-model="entity.ApplicationPerson" :disabled="disabled" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="出发城市:" :rules="$rules.handle.DepartureCityName" required
					name="DepartureCityName">
					<uni-data-picker popup-title="请选择出发城市" :localdata="dataTree"
						@change="pickerChange($event, 'DepartureCityName')" :inputBorder="false" :readonly="disabled"
						v-model="entity.DepartureCityName">
					</uni-data-picker>
				</uni-forms-item>
				<uni-forms-item label="出发日期:" :rules="$rules.handle.DepartureDate" required name="DepartureDate">
					<view @click="DateChange($event, 'DepartureDate')">
						<uni-easyinput v-model="entity.DepartureDate" :disabled="true" :inputBorder="false" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="上下午:" :rules="$rules.handle.DepartureAMPM" required name="DepartureAMPM">
					<uni-data-select :clear="false" style="background-color: #fff;border-radius: 10rpx;"
						v-model="entity.DepartureAMPM" :localdata="DepartureAMPMOptions"
						@change="selectOptionsChange($event, 'DepartureAMPM')" :disabled="disabled"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="返回日期:" :rules="$rules.handle.ReturnDate" required name="ReturnDate">
					<view @click="DateChange($event,'ReturnDate')">
						<uni-easyinput v-model="entity.ReturnDate" :disabled="true" :inputBorder="false" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="上下午:" :rules="$rules.handle.ArrivalAMPM" required name="ArrivalAMPM">
					<uni-data-select :clear="false" style="background-color: #fff;border-radius: 10rpx;"
						v-model="entity.ArrivalAMPM" :localdata="ArrivalAMPMOptions"
						@change="selectOptionsChange($event, 'ArrivalAMPM')" :disabled="disabled"></uni-data-select>
				</uni-forms-item>

				<uni-forms-item label="票面总金额:" name="FaceAmount">
					<view>
						<uni-easyinput v-model="entity.FaceAmount" :disabled="true" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="报销总金额:" name="ReimburseAmount">
					<view>
						<uni-easyinput v-model="entity.ReimburseAmount" :disabled="true" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="出差天数:" name="TravelDays">
					<view>
						<uni-easyinput v-model="entity.TravelDays" :inputBorder="false" :disabled="true" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="补贴基数:" name="SubsidyBase">
					<view>
						<uni-easyinput v-model="entity.SubsidyBase" :inputBorder="false" :disabled="true" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="出差补贴:" name="TravelAllowance">
					<view>
						<uni-easyinput v-model="entity.TravelAllowance" :disabled="true" />
					</view>
				</uni-forms-item>

				<uni-forms-item label="财务摘要:">
					<view>
						<uni-easyinput v-model="entity.Abstract" type="textarea" maxlength="300" :disabled="disabled" />
					</view>
				</uni-forms-item>
			</view>

			<!-- 添加行程明细 -->
			<view v-if="!disabled" class="flex  Jbetween">
				<uni-section title="行程信息" type="line"></uni-section>
				<view class="flex Acenter Jbetween" @click="AddDetailClick">
					<u-icon name="plus-circle-fill" color="#2979ff" size="45"></u-icon>
					<text style="color:#2979ff;font-weight:bold;padding-left: 10rpx;">{{addButton}}</text>

				</view>
			</view>

			<view class="scrollBox">
				<scroll-view style="width: 100%;height: 100%;" scroll-y="true">
					<view style="padding-bottom: 50px;padding-left: 15rpx;padding-right: 15rpx;">
						<view class="detail" v-for="(item, index) in tripDetailData" :key="index">
							<view class="" style="font-size: 14px">
								<span class="font" style="margin-right: 30rpx;"># {{ index +1 }}</span>
								<view class="flex Jbetween">
									<span class="font">行程名称: {{item.ItineraryName}}</span>
									<span class="font">交通方式:
										{{item.ModeTransportationName }}</span>
								</view>

								<view class="flex Jbetween">
									<span class="font">到达城市: {{item.newArrivalCityIdName}}</span>
								</view>
								<view class="flex Jbetween">
									<span class="font">到达日期: {{ item.ArrivalDate}}</span>
								</view>
								<view class="flex Jbetween">
									<span class="font">关联客户: {{ item.CustomerName}}</span>
								</view>
								<view class="flex Jbetween">
									<span class="font">客户拜访说明: {{item.Infor}}</span>
								</view>
							</view>
							<view v-if="!disabled" class="flex Jend">
								<view @click.stop="handleItemEdit(entity, item, index)" style="
								  width: 15%;
								  border-radius: 5px;
								  line-height: 30px;
								  color: #fff;
								  text-align: center;
								  margin-top: 10rpx;
								  background-color: #2979ff;
								  margin-right: 30rpx;
								">
									修改
								</view>
								<view @click="detailDataDelete([item.Id], index)" style="
							  width: 15%;
							  border-radius: 5px;
							  line-height: 30px;
							  color: #fff;
							  text-align: center;
							  background-color: red;
							  margin-top: 10rpx;
							">
									删除
								</view>
							</view>
							<view v-else class="flex Jend">
								<view @click.stop="handleItemDetail(entity, item, index)" style="
								  width: 15%;
								  border-radius: 5px;
								  line-height: 30px;
								  color: #fff;
								  text-align: center;
								  margin-top: 10rpx;
								  background-color: #2979ff;
								">
									查看
								</view>
							</view>
						</view>
						<view v-if="tripDetailData" style="margin: 50rpx 0;">
							<u-empty v-if="tripDetailData.length==0" text="请添加行程" mode="list"></u-empty>
						</view>
					</view>
				</scroll-view>
			</view>
			<view v-if="options.ActivityName ==='开始'">
				<view class="submitButton" style="display: flex;align-items: center;">
					<u-button type="primary" plain style="font-size: 14px;width: 200rpx;" @click="onSubmit(0)"
						:loading="loading">保存草稿</u-button>
					<u-button type="primary" style="font-size: 14px;width: 200rpx;" @click="onSubmit(1)"
						:disabled="isButtonDisabled" :loading="loading">提交</u-button>
				</view>
			</view>
			<view v-else-if="options.ActivityName === 'null'">
			</view>
			<view v-else>
				<view class="submitButton" style="display: flex;align-items: center;">
					<u-button type="default" plain style="font-size: 14px;width: 200rpx;" @click="urlBack"
						:loading="loading">返回</u-button>
					<u-button type="primary" style="font-size: 14px;width: 200rpx;" @click="onSubmit(2)"
						:loading="loading">审批</u-button>
				</view>
			</view>
		</uni-forms>


		<!-- 审批弹窗 -->
		<uni-popup ref="inputDialog" type="dialog">
			<!-- 后续使用该样式直接打开即可 position: absolute;right: 20rpx;top: 20rpx; color="#909390"-->
			<view style="display: flex;justify-content: flex-end;margin-bottom: 10rpx;">
				<uni-icons type="closeempty" size="30" @click="$refs.inputDialog.close()"></uni-icons>
			</view>
			<uni-popup-dialog cancelText="不同意" confirmText="同意" title="审批意见" type="info" :value="comment"
				@close="dialogInputHandleSubmit(2)" @confirm="dialogInputHandleSubmit(1)" before-close>
				<uni-easyinput type="textarea" v-model="comment" placeholder="请输入审批意见" :adjust-position="false" />
			</uni-popup-dialog>
		</uni-popup>

		<!-- 选择日期 -->
		<u-calendar v-model="isCalendar" :mode="mode" placeholder="请选择日期" @change="calendarChange"></u-calendar>
		<!-- 引用公司子组件 -->
		<Company ref="Company" @change="changeHandler" @cancel="$refs.Company.close()" :title="title"></Company>
	</view>
</template>

<script>
	// 开始日期上下午
	const DepartureAMPMOptions = [{
			value: 1,
			text: '上午'
		},
		{
			value: 2,
			text: '下午'
		}
	]
	// 结束日期上下午
	const ArrivalAMPMOptions = [{
			value: 1,
			text: '上午'
		},
		{
			value: 2,
			text: '下午'
		}
	]
	import {
		mapState
	} from "vuex";
	// 引用公司选择子组件
	import Company from '@/components/Company.vue'
	import AddDetail from './AddDetail.vue';
	// 引用报销明细和补贴明细
	import ApplyReimDetails from './TravelDetailList/ApplyReimDetails.vue';
	import SubsidyDetails from './TravelDetailList/SubsidyDetails.vue'
	// 引入公共接口文件
	import {
		//获取公司列表数据
		CompanyDataList,
		// 获取部门下拉列表
		DepartmentList,
		// 获取差旅报销单主表详情
		Reimburse_Travel_Business_MainGetTheData,
		// 差旅审批提交
		Ai_WorkitemTravelApproved,
		// 差旅保存修改 临时保存草稿
		Reimburse_Travel_Business_MainSaveData,
		// 差旅报销单 行程子表删除
		Reimburse_Travel_Business_ItemDeleteData,
		// 判断姓名是否存在人员档案中
		Base_UserGetExistEmployee
	} from "@/api/interface.js";
	export default {
		components: {
			// 公司组件
			Company,
			// 新增明细表单组件
			AddDetail,
			// 报销明细
			ApplyReimDetails,
			// 补贴明细
			SubsidyDetails
		},
		data() {
			return {
				// 出发日期上下午
				DepartureAMPMOptions,
				// 返回日期上下午
				ArrivalAMPMOptions,
				// 添加明细按钮类别
				addButton: "添加行程与客户拜访",
				// 是否允许提交按钮
				isButtonDisabled: false,
				// 公司和部门弹窗的标题
				title: "请选择公司",
				// 审批意见
				comment: '',
				// 顶部导航栏切换
				tabsList: [{
					name: '行程信息'
				}, {
					name: '报销明细'
				}],
				// 地区树结构
				dataTree: [],
				// 默认选中tab
				currentIndex: 0,
				// 禁用
				disabled: false,
				// 禁用部门名称
				disabledDeptName: false,
				// 加载
				loading: false,
				entity: {
					// 票面总金额
					FaceAmount: '',
					// 报销总金额
					ReimburseAmount: '',
					// ********************************************默认赋值空值  否则提交会有校验不通过问题********************************************
					DeptName: ""

				},
				// 交通方式下拉列表数据
				ModeTransportationOptions: [],
				// 是否显示日期弹窗
				isCalendar: false,
				// 日期选择
				mode: 'date',
				// 是否展示公司选择底部弹窗组件
				showPopup: false,
				// 底部弹窗列表数据
				columns: [],
				// 点击弹出底部弹窗的字段类型
				dataType: "",
				options: {},
				// 行程子表
				tripDetailData: [],
				// 报销子表
				detailData: [],
				// 补贴明细
				subDetailData: [],
				// 附件列表
				reimburse_Files: [],
				Upload: [],
				// 报销子表编辑点击下标当前行
				detailDataIndex: 0,
				// 补贴子表编辑点击下标当前行
				subDetailDataIndex: 0


			}
		},
		computed: {
			...mapState(["UserInfo", "BillTypeOptions", "ExpenseTypeOptions", "InvoiceClassificationOptions",
				"CompayListOptions", "Base_DistrictGetTreeDataOptions", "Base_DistrictGetTreeDataTListOptions",
				"TransportationModeOptions",
				"CustomerInfoOptions"
			]),
		},
		onShow() {
			//默认赋值当前选择日期
			let time = this.$moment().format("YYYY-MM-DD");
			this.entity.ApplicationDate = time
		},
		onLoad(options) {
			// 出发城市的确树结构 二级
			this.dataTree = this.Base_DistrictGetTreeDataTListOptions
			// 交通方式下拉列表数据
			this.ModeTransportationOptions = this.TransportationModeOptions
			this.options = options
			uni.setNavigationBarTitle({
				title: '修改差旅报销单'
			})
			// 判断是否是查看条件
			if (this.options.disabled === "true") {
				this.disabled = true
				uni.setNavigationBarTitle({
					title: '差旅报销单详情'
				})
			} else {
				this.disabled = false
			}
			this.disabledDeptName = true
			console.log('是否查看---------', this.options)
			this.$forceUpdate()
			// // 公司名称
			// let CompanyName = this.CompayListOptions.filter(item => item.value === this.UserInfo.UserInfo.CompanyId)[0]
			// 	.text
			// // 公司id
			// let CompanyId = this.CompayListOptions.filter(item => item.value === this.UserInfo.UserInfo.CompanyId)[0]
			// 	.value
			// // 默认取当前用户公司名称和id
			// this.$set(this.entity, 'CompanyName', CompanyName)
			// this.$set(this.entity, 'CompanyId', CompanyId)
			// // 报销人姓名默认赋值
			// this.$set(this.entity, 'ApplicationPerson', this.UserInfo.UserInfo.StaffName)
			// if (this.entity.CompanyId) {
			// 	// 默认取当前公司id下的部门名称和id
			// 	// 获取部门下拉列表
			// 	this.getDepartmentList('默认', CompanyId)
			// }

			// 获取差旅报销单主表详情
			this.getReimburse_Travel_Business_MainGetTheData(this.options.ApprovalFormId)
			console.log('详情详情详情详情详情详情详情详情差旅传递过来的c撑死树结构optionsoptionsoptions', options)
		},

		methods: {
			// 处理出发城市到达城市回显
			getBase_DistrictGetTreeDataOptionsName(itemEntity) {

				// 主表里的出发城市回显
				let DepartureCity = this.entity.DepartureCity ? this.entity.DepartureCity.split('/') : []
				// 子表里的到达城市回显
				let ArrivalCityId = itemEntity.ArrivalCityId ? itemEntity.ArrivalCityId.split('/') : []
				// 主表里的出发城市存储
				let entityDepartureCityNameArr = []
				// 存储出发城市
				let DepartureCityNameArr = []
				// 存储到达城市
				let ArrivalCityIdNameArr = this.$getDicNames(ArrivalCityId, this.Base_DistrictGetTreeDataOptions)


				// 	// 处理出发城市和到达城市回显
				if (this.Base_DistrictGetTreeDataOptions) {
					this.Base_DistrictGetTreeDataOptions.forEach((item) => {

						// 子表里的出发城市和到达城市回显
						if (item.Id === DepartureCity[0]) {
							DepartureCityNameArr.push(item.Text)
						}
						// 过滤到达城市数组
						// if (item.Id === ArrivalCityId[0]) {
						// 	ArrivalCityIdNameArr.push(item.Text)
						// }
						if (item.children) {
							item.children.forEach((v) => {

								// 过滤出发城市children里层
								if (v.Id === DepartureCity[1]) {
									DepartureCityNameArr.push(v.Text)
								}
								// 过滤到达城市children里层
								// if (v.Id === ArrivalCityId[1]) {
								// 	ArrivalCityIdNameArr.push(v.Text)
								// }
							})
						}
					})
				}
				// 单独处理行程子表里的明细子表业务性质回显
				if (itemEntity.reimburse_Travel_Business_SubsidyDTOs && itemEntity.reimburse_Travel_Business_SubsidyDTOs
					.length > 0) {
					itemEntity.reimburse_Travel_Business_SubsidyDTOs.forEach(item => {

						// 单独处理报行程的费用明细子表附件名称
						// 处理附件的名称
						if (item.reimburse_Files) {
							let arr = []
							item.reimburse_Files.forEach(v => {
								if (v.FilePath) {
									v.FileName = v.FilePath.split('/').pop()
									let obj = {
										fileEntity: v
									}
									arr.push(obj)
									item.reimburse_Files = arr
								}

							})
						}

						// 票据日期格式化
						// 日期格式化
						item.BillDate = this.$moment(item.BillDate).format("YYYY-MM-DD")
						// 单独处理行程明细里的费用子表明细客户多选回显
						// 行程子表里的行程明细子表关联客户回显 
						if (item.CustomId) {
							let CustomIdArr = item.CustomId.split(',')
							// 客户名称存储
							let newCustomerNameArr = []
							// 客户id存储
							let newCustomIdArr = []
							// 存储选中好的客户下拉数据 用于后续页面数据处理使用
							let CustomerNameOptions = []
							// 过滤公司名称和公司id
							this.CustomerInfoOptions.forEach(v => {
								CustomIdArr.forEach(m => {
									if (m === v.value) {
										newCustomerNameArr.push(v.text ? v.text : v
											.cCusName)
										newCustomIdArr.push(v.value ? v.value : v
											.Id)
										CustomerNameOptions.push(v)
									}
								})
							})
							item.CustomId = newCustomIdArr.join(',')
							item.CustomerName = newCustomerNameArr.join(',')
							item.CustomerNameOptions = CustomerNameOptions
						}

						// 暂时不删除
						// if (item.CustomId) {
						// 	let CustomerName = this.CustomerInfoOptions.filter(v => v.value ===
						// 		item.CustomId)[0] ? this.CustomerInfoOptions.filter(v => v
						// 		.value === item.CustomId)[0].text : item.CustomId
						// 	// 用于回显
						// 	item.CustomerName = CustomerName
						// 	// 用于后续数据吹
						// 	item.CustomerNameOptions = this.CustomerInfoOptions.filter(v => v.value ===
						// 		item.CustomId)
						// }
						// 发票分类类型回显
						if (item.InvoiceClassification) {

							item.InvoiceClassificationName = this.InvoiceClassificationOptions
								.filter(
									v => v.value === item.InvoiceClassification)[0] ?
								this.InvoiceClassificationOptions.filter(v => v.value === item
									.InvoiceClassification)[0].text : item.InvoiceClassification
						}
						// // 票据类型回显
						if (item.BillType) {
							item.BillTypeName = this.BillTypeOptions.filter(v => v.value === item
									.BillType)[0] ?
								this.BillTypeOptions.filter(v => v.value === item.BillType)[0]
								.text :
								item.BillType
						}

						// 业务性质回显

						if (item.ExpenseTypeId) {
							// 存储业务性质
							let ExpenseTypeNameArr = []
							// 业务性质名称
							let ExpenseType = item.ExpenseType.split('/')
							// 业务性质id
							let ExpenseTypeId = item.ExpenseTypeId.split('/')

							console.log('处理业务性质回显', ExpenseType, ExpenseTypeId, item)
							// // 业务性质回显 用于处理数据
							let ExpenseTypeName = [{
								value: ExpenseTypeId[0],
								text: ExpenseType[0]
							}, {
								value: ExpenseTypeId[1],
								text: ExpenseType[1]
							}]
							// // 用于回显名字
							this.$set(item, 'newExpenseTypeName', item.ExpenseType)
							// // 用于数据处理回显
							this.$set(item, 'ExpenseTypeName', ExpenseTypeName)
						}


					})
				}

				let ArrivalCityIdName = [{
					value: ArrivalCityId[0],
					text: ArrivalCityIdNameArr[0]
				}, {
					value: ArrivalCityId[1],
					text: ArrivalCityIdNameArr[1]
				}, {
					value: ArrivalCityId[2],
					text: ArrivalCityIdNameArr[2]
				}]
				// 到达城市名称回显  子表的
				this.$set(itemEntity, 'newArrivalCityIdName', ArrivalCityIdNameArr.join('/'))
				// 单独处理到达城市数组 用于回显
				this.$set(itemEntity, 'ArrivalCityIdName', ArrivalCityIdName)
				let DepartureCityName = [{
					value: DepartureCity[0],
					text: DepartureCityNameArr[0]
				}, {
					value: DepartureCity[1],
					text: DepartureCityNameArr[1]
				}]

				// // 	// 报销单出发城市名称回显
				this.$set(this.entity, 'DepartureCityName', DepartureCityName)
				// /处理id
				this.$set(this.entity, 'DepartureCity', DepartureCity[0] + '/' + DepartureCity[1])



				this.$forceUpdate()
			},
			// 返回
			urlBack() {
				uni.navigateBack()
			},
			// 日期时间选择
			DateChange(event, type) {
				if (this.disabled) return
				this.dataType = type
				this.isCalendar = true
			},
			// 日期选择calendarChange
			calendarChange(event) {

				// *************注意  存储必须用set赋值  否则校验不通过   ************************************
				this.$set(this.entity, this.dataType, event.result);
				// *************注意  存储必须用set赋值  否则校验不通过   ************************************

				//当前选择日期
				// 判断出发和返回日期比较
				// let ApplicationDate = new Date(this.$moment().format("YYYY-MM-DD"));
				console.log('确认日期了', this.entity, event, this.DateType)
				// 判断开始日期是否大于当天日期
				if (this.entity.DepartureDate && this.entity.ReturnDate) {
					// 出发日期
					let DepartureDate = new Date(this.entity.DepartureDate);
					// 返回日期
					let ReturnDate = new Date(this.entity.ReturnDate);
					if (DepartureDate > ReturnDate) {
						this.$errorToast('出发日期不能大于返回日期')
						if (this.DateType === 'DepartureDate') {
							delete this.entity.DepartureDate
						} else {
							delete this.entity.ReturnDate
						}
						return
					}
				}


				let AMPM = 0
				if (this.entity.DepartureAMPM == 1 && this.entity.ArrivalAMPM == 1) {
					AMPM = 0.5
				} else if (this.entity.DepartureAMPM == 2 && this.entity.ArrivalAMPM == 2) {
					AMPM = 0.5
				} else if (this.entity.DepartureAMPM == 1 && this.entity.ArrivalAMPM == 2) {
					AMPM = 1
				} else if (this.entity.DepartureAMPM == 2 && this.entity.ArrivalAMPM == 1) {
					AMPM = 1
				}
				if (this.entity.DepartureDate && this.entity.ReturnDate) {
					const totalDays = Number(this.getDiffDay(this.entity.DepartureDate, this.entity.ReturnDate)) + AMPM
					// 自动计算出差补贴   补贴基数*出差天数
					this.entity.TravelAllowance = totalDays * this.entity.SubsidyBase
					// 赋值当前行的出差天数
					this.entity.TravelDays = totalDays
				}

				console.log('选择日期确定了', event, this.dataType, this.entity)
			},
			// 出发城市和到达城市
			pickerChange(event, key) {
				console.log('出发城市选择了', event, key, this.entity)
				let arr = event.detail.value
				// 出发城市名称
				let DepartureCityName = arr.map(item => {
					return item.text
				}).join('/')
				// 出发城市id
				let DepartureCity = arr.map(item => {
					return item.value
				}).join('/')
				this.$set(this.entity, 'newDepartureCity', DepartureCity)
				this.$set(this.entity, 'newDepartureCityName', DepartureCityName)
				this.$set(this.entity, 'DepartureCityName', event.detail.value)
			},
			getDiffDay(date_1, date_2) {
				// 计算两个日期之间的差值
				let totalDays, diffDate
				const myDate_1 = Date.parse(date_1)
				const myDate_2 = Date.parse(date_2)
				// 将两个日期都转换为毫秒格式，然后做差
				diffDate = Math.abs(myDate_1 - myDate_2) // 取相差毫秒数的绝对值
				totalDays = Math.floor(diffDate / (1000 * 3600 * 24)) // 向下取整
				// console.log(totalDays)
				return totalDays // 相差的天数
			},
			// 上午下午下拉改变事件
			selectOptionsChange(event, key) {

				let optionsArr = []

				if (key === 'DepartureAMPM') {
					// 开始日期上下午
					optionsArr = this.DepartureAMPMOptions
				} else {
					//结束日期上下午
					optionsArr = this.ArrivalAMPMOptions
				}
				// 上下午名称
				let Name = optionsArr.filter(item => item.value === event)[0].text
				this.$set(this.entity, key + 'Name', Name)

				let AMPM = 0
				if (this.entity.DepartureAMPM == 1 && this.entity.ArrivalAMPM == 1) {
					AMPM = 0.5
				} else if (this.entity.DepartureAMPM == 2 && this.entity.ArrivalAMPM == 2) {
					AMPM = 0.5
				} else if (this.entity.DepartureAMPM == 1 && this.entity.ArrivalAMPM == 2) {
					AMPM = 1
				} else if (this.entity.DepartureAMPM == 2 && this.entity.ArrivalAMPM == 1) {
					AMPM = 1
				}
				if (this.entity.DepartureDate && this.entity.ReturnDate) {
					const totalDays = Number(this.getDiffDay(this.entity.DepartureDate, this.entity.ReturnDate)) + AMPM
					// 自动计算出差补贴   补贴基数*出差天数
					this.entity.TravelAllowance = totalDays * this.entity.SubsidyBase
					// 赋值当前行的出差天数
					this.entity.TravelDays = totalDays
				}
				// // 同时计算应付金额 = 报销总金额 + 出差补贴
				this.entity.PayableAmount = this.entity.ReimburseAmount + this.entity.TravelAllowance
				console.log('上下午选择改变了', event, key, this.entity)
			},
			// 行程子表编辑
			handleItemEdit(entity, item, index) {
				console.log('行程子表编辑', entity, item, index)
				let data = {
					entity: entity,
					item: item
				}
				uni.setStorageSync('entity', data)
				// 子表报销编辑
				this.detailDataIndex = index
				uni.navigateTo({
					url: "/pages/Approval/EditDetailTrip"
				})
			},
			// 查看
			handleItemDetail(entity, item, index) {
				console.log('查看', entity, item, index)

				let data = {
					entity: entity,
					item: item,
					disabled: true
				}
				uni.setStorageSync('entity', data)
				// 子表报销编辑
				this.detailDataIndex = index
				uni.navigateTo({
					url: "/pages/Approval/EditDetailTrip"
				})
			},
			// 行程子表删除
			detailDataDelete(rowId, index) {
				console.log('行程子表开始删除了------------', rowId, index)
				var that = this
				this.$utils.showConfirm({
					content: '确定要删除吗',
					confirmText: "删除",
					confirmColor: "#D1100b"
				}).then(res => {
					if (res.confirm) {
						// 视图删除
						if (rowId[0] == undefined) {
							// 视图删除
							that.tripDetailData.splice(index, 1)
							that.$sucessToast('已删除')
							return
						}
						uni.showLoading({
							title: '删除中'
						})
						this.loading = true
						Reimburse_Travel_Business_ItemDeleteData(rowId).then(resJson => {
							if (resJson.Success) {
								// 视图删除
								that.tripDetailData.splice(index, 1)
								that.$sucessToast('已删除')
								setTimeout(function() {
									that.loading = false
									uni.hideLoading()
								}, 2500)

							} else {
								that.$errorToast(resJson.Msg);
								setTimeout(function() {
									that.loading = false
									uni.hideLoading()
								}, 2500)
							}
						})
					} else {
						this.loading = false;
					}
				})
				// 重新计算总金额
				this.getTotalAmount()
			},
			// push报销明细子表
			setDetailData(type, key, data) {
				console.log('报销和补贴子表过来的--------', type, key, data)
				// 处理到达城市数组回显字符串
				// if (typeof(data.ArrivalCityIdName) === 'object') {
				// 	data.ArrivalCityIdName = data.ArrivalCityIdName.map(item => {
				// 		return item.text
				// 	}).join('/')
				// }
				if (type === 'add') {
					this.tripDetailData.push(data)
					console.log('新增过来的行程信息', data, this.tripDetailData)
				} else {
					let tripDetailData = this.tripDetailData
					console.log('编辑过来的行程信息', data, tripDetailData)
					tripDetailData.forEach((item, index) => {
						if (item.Id && item.Id === data.Id) {
							tripDetailData[index] = data
						} else {
							// 替换数组里对应对象
							this.tripDetailData.splice(this.detailDataIndex, 1, data)
						}
					})
				}
				// 计算票面总金额和报销总金额
				this.getTotalAmount()
				this.$forceUpdate()
			},
			// 求和函数
			sumObjects(arr, key) {
				return arr.reduce((sum, current) => sum + parseFloat(current[key] || 0), 0)
			},

			// 计算票面总金额和报销总金额
			getTotalAmount() {

				this.tripDetailData.forEach(item => {
					if (item.detailData && item.detailData.length > 0) {
						// 计算票面总金额
						const newFaceAmount = this.sumObjects(item.detailData, 'FaceAmount')
						// 计算报销总金额
						const newReimburseAmount = this.sumObjects(item.detailData, 'ReimburseAmount')
						// 计算差额
						const totalDifference = newFaceAmount - newReimburseAmount
						// 票面总金额和报销总金额赋值entity
						// 每一个的报销金额
						item.newFaceAmount = newFaceAmount
						// 每一个的报销金额
						item.newReimburseAmount = newReimburseAmount
						// 每一个的应付金额
						item.newPayableAmount = newReimburseAmount
						// 每一个的差额赋值
						item.newDifference = totalDifference

					}
				})


				// entity李的票面总金额和报销总金额就散
				// 票面总金额
				const totalFaceAmount = this.sumObjects(this.tripDetailData, 'newFaceAmount')
				// 报销总金额
				const totalReimburseAmount = this.sumObjects(this.tripDetailData, 'newReimburseAmount')
				// 计算总的应付金额 // 同时计算应付金额 = 报销总金额 + 出差补贴
				const totalPayableAmount = totalReimburseAmount + Number(this.entity.TravelAllowance ? this.entity
					.TravelAllowance : 0)
				// 赋值entity 票面总金额 
				this.entity.FaceAmount = totalFaceAmount
				// 赋值entity报销总金额
				this.entity.ReimburseAmount = totalReimburseAmount
				// 赋值entity应付金额
				this.entity.PayableAmount = totalPayableAmount
				// 应付金额赋值后实时更新大写
				const value = this.$utils.transformToUppercase(this.entity.PayableAmount)
				this.entity.Capitalization = value
				console.log('开始计算总额了', this.tripDetailData, totalFaceAmount, totalReimburseAmount, totalPayableAmount)
				console.log('计算后的entity', this.entity)
				// this.entity.FaceAmount = newFaceAmount
				// this.entity.ReimburseAmount = newReimburseAmount
				// // 差额赋值
				// this.entity.Difference = totalDifference
				// // 应付金额赋值
				// this.entity.PayableAmount = newReimburseAmount
				// if (this.subDetailData.length > 0) {
				// 	// 计算出差补贴总金额
				// 	const TravelAllowanceSummary = this.sumObjects(this.subDetailData, 'TravelAllowance')
				// 	this.entity.TravelAllowance = TravelAllowanceSummary
				// }
				// // // 同时计算应付金额 = 报销总金额 + 出差补贴
				// this.entity.PayableAmount = this.entity.ReimburseAmount + this.entity.TravelAllowance
				// // 应付金额赋值后实时更新大写
				// const value = this.$utils.transformToUppercase(this.entity.PayableAmount)
				// // 大写赋值
				// this.entity.Capitalization = value
			},
			// 添加行程
			AddDetailClick() {
				//添加行程
				uni.navigateTo({
					url: "/pages/Approval/AddDetailTrip"
				})
			},
			// 审批意见 同意  -不同意
			dialogInputHandleSubmit(type) {
				var that = this
				let obj = {}
				if (type == 1) {
					obj.Id = this.options.ApprovalFormId
					obj.comment = this.comment
					obj.flag = true
				} else {
					obj.Id = this.options.ApprovalFormId
					obj.comment = this.comment
					obj.flag = false
				}
				this.loading = true
				uni.showLoading({
					title: '审批中'
				})
				// 差旅审批提交
				Ai_WorkitemTravelApproved(obj).then(resJson => {
					if (resJson.Success) {
						this.$sucessToast('审批成功')
						setTimeout(function() {
							that.loading = false
							uni.navigateBack()
							uni.hideLoading()
						}, 2500)

					} else {
						this.$errorToast(resJson.Msg)
						setTimeout(function() {
							that.loading = false
							uni.navigateBack()
							uni.hideLoading()
						}, 2500)
					}

				})
				// 关闭 弹窗
				this.$refs.inputDialog.close()
			},
			// 获取差旅报销单主表详情
			getReimburse_Travel_Business_MainGetTheData(id) {
				console.log('详情传递', id)

				uni.showLoading({
					title: '加载中'
				})
				Reimburse_Travel_Business_MainGetTheData({
					id: id
				}).then(resJson => {

					if (resJson.Success) {
						uni.hideLoading()
						this.entity = resJson.Data
						this.$forceUpdate()
						// 获取部门下拉列表
						this.getDepartmentList('默认', this.entity.CompanyId)
						// 申请日期格式化
						this.entity.ApplicationDate = this.$moment(resJson.Data.ApplicationDate).format(
							"YYYY-MM-DD")
						// 出发日期格式化
						this.entity.DepartureDate = this.$moment(resJson.Data.DepartureDate).format(
							"YYYY-MM-DD")
						// 返回日期格式化
						this.entity.ReturnDate = this.$moment(resJson.Data.ReturnDate).format(
							"YYYY-MM-DD")
						// 出发和返回上下午 狐仙格式化
						this.entity.DepartureAMPM = Number(this.entity.DepartureAMPM)
						this.entity.ArrivalAMPM = Number(this.entity.ArrivalAMPM)

						// /公司下拉回显
						this.entity.CompanyName = this.CompayListOptions.filter(item => item.value === resJson.Data
							.CompanyId)[0].text
						// // 补贴基数赋值
						this.entity.SubsidyBase = this.entity.SubsidyBase ? this.entity.SubsidyBase : this.UserInfo
							.UserInfo
							.TravelSubsidyBase

						// 主表里的出发城市回显
						let DepartureCity = this.entity.DepartureCity ? this.entity.DepartureCity.split('/') : []
						// 主表里的出发城市回显
						// 存储出发城市
						let DepartureCityNameArr = []
						// 	// 处理出发城市和到达城市回显
						if (this.Base_DistrictGetTreeDataOptions) {
							this.Base_DistrictGetTreeDataOptions.forEach((item) => {

								// 子表里的出发城市和到达城市回显
								if (item.Id === DepartureCity[0]) {
									DepartureCityNameArr.push(item.Text)
								}
								if (item.children) {
									item.children.forEach((v) => {
										// 过滤出发城市children里层
										if (v.Id === DepartureCity[1]) {
											DepartureCityNameArr.push(v.Text)
										}
									})
								}
							})
						}
						let DepartureCityName = [{
							value: DepartureCity[0],
							text: DepartureCityNameArr[0]
						}, {
							value: DepartureCity[1],
							text: DepartureCityNameArr[1]
						}]
						console.log('主表里的城市回显--', DepartureCityName)
						// // 	// 报销单出发城市名称回显
						this.$set(this.entity, 'DepartureCityName', DepartureCityName)
						// /处理id
						this.$set(this.entity, 'DepartureCity', DepartureCity[0] + '/' + DepartureCity[1])

						// 行程子表回显
						if (resJson.Data.reimburse_Travel_Business_ItemDTOs !== null) {

							resJson.Data.reimburse_Travel_Business_ItemDTOs.forEach(item => {
								// 判断行程子表里是否存在行程子表的费用明细  如果没有返回 赋值默认空数组  否则后续可能会出现报错
								if (!item.reimburse_Travel_Business_SubsidyDTOs) {
									item.reimburse_Travel_Business_SubsidyDTOs = []
								}
								// 	// 日期格式化
								item.ArrivalDate = this.$moment(item.ArrivalDate).format(
									"YYYY-MM-DD")
								// 交通方式回显
								if (item.TransportationMode) {
									item.ModeTransportationName = this.TransportationModeOptions.filter(
										v => v
										.value === item.TransportationMode)[0].text
								}

								// 详情处理出发城市到达城市回显
								this.getBase_DistrictGetTreeDataOptionsName(item)
								// 行程子表哦关联客户回显
								if (item.CustomId) {

									let CustomIdArr = item.CustomId.split(',')
									// 客户名称存储
									let newCustomerNameArr = []
									// 客户id存储
									let newCustomIdArr = []
									// 存储选中好的客户下拉数据 用于后续页面数据处理使用
									let CustomerNameOptions = []
									// 过滤公司名称和公司id
									this.CustomerInfoOptions.forEach(v => {
										CustomIdArr.forEach(m => {
											if (m === v.value) {
												newCustomerNameArr.push(v.text ? v.text : v
													.cCusName)
												newCustomIdArr.push(v.value ? v.value : v
													.Id)
												CustomerNameOptions.push(v)
											}
										})
									})

									item.CustomId = newCustomIdArr.join(',')
									item.CustomerName = newCustomerNameArr.join(',')
									item.CustomerNameOptions = CustomerNameOptions

									console.log('详情处理客户下拉了', item)
								}


							})
						}
						// 差旅行程子表回显
						this.tripDetailData = resJson.Data.reimburse_Travel_Business_ItemDTOs
						this.$forceUpdate()
						//  let CompanyName = null
						//           this.CompanyIdTreeData.forEach((item) => {
						//             if (item.Id === CompanyId) {
						//               CompanyName = item.TypeName
						//             }
						//           })

						//           // 选择公司赋值
						//           this.entity.CompanyName = CompanyName
					}
				})

			},
			// 公司选择
			CustomerChoice(value) { // 获取公司下拉列表数据
				if (this.disabled) return
				this.dataType = ""
				this.dataType = value
				// 判断公司名称是否为空  再点击部门选择的时候
				if (value === 'DeptName') {
					if (!this.entity.CompanyName) {
						// 如果没有公司先禁用部门名称
						this.disabledDeptName = true
						this.$errorToast('请先选择公司')
						return
					}
				}
				if (value === 'CompanyName') {
					// 获取公司下拉列表数据
					this.getCompanyDataList()
				} else {
					console.log('打开部门弹窗了', this.entity, )
					this.title = "请选择部门"
					if (this.entity.CompanyId) {
						// 获取部门下拉列表
						this.getDepartmentList('选择', this.entity.CompanyId)
					}
				}


			},
			// 获取部门列表数据
			// 底部弹窗选中事件
			changeHandler(children) {
				if (children) {
					// 如果选择公司了.打开部门名称
					this.disabledDeptName = false
				}
				// 公司和部门名称id赋值
				if (this.dataType === 'CompanyName') {
					// 重新选择公司名称  初始化部门名称和id
					this.entity.DeptName = ""
					this.entity.DepartmentId = ""
					this.$set(this.entity, "CompanyName", children.label);
					this.$set(this.entity, "CompanyId", children.value);
				} else {
					this.$set(this.entity, "DeptName", children.label);
					this.$set(this.entity, "DepartmentId", children.value);
				}

				this.$forceUpdate()
				// 隐藏底部弹窗
				this.$refs.Company.close()
			},
			//获取公司列表数据
			getCompanyDataList() {
				CompanyDataList({}).then(resJson => {
					if (resJson.Success) {
						this.columns = resJson.Data.map(item => {
							return {
								value: item.Id,
								label: item.title
							}
						})

					}
					this.$refs.Company.open(this.columns)
				})
			},
			// 获取部门下拉列表
			getDepartmentList(type, CompanyId) {
				DepartmentList({
					DeptId: CompanyId
				}).then(resJson => {
					if (resJson.Success) {
						this.columns = resJson.Data.map(item => {
							return {
								value: item.Id,
								label: item.Name
							}
						})
						// /如果是默认过来的
						if (type === '默认') {
							this.entity.DeptName = ""
							this.entity.DepartmentId = ""
							// 部门的名称和id回显
							let DeptName = this.columns.filter(item => item.value === this.UserInfo
								.UserInfo.DepartId)[0].label
							let DepartmentId = this.columns.filter(item => item.value === this.UserInfo
								.UserInfo.DepartId)[0].value
							this.$set(this.entity, 'DeptName', DeptName)
							this.$set(this.entity, 'DepartmentId', DepartmentId)
							// 强制更新
							this.$forceUpdate()
							return
						} else {
							// 否则走下拉选择逻辑
							this.$refs.Company.open(this.columns)
						}

					}
				})
			},
			// 提交
			onSubmit(type) {
				var that = this
				// 如果点击的是审批按钮
				if (type == 2) {
					this.comment = ""
					// 点击的是审批
					this.$refs.inputDialog.open()
					return
				}


				// 判断报销人姓名是否存在人员档案中  不存在  禁止保存和提交
				Base_UserGetExistEmployee({
					staffName: this.entity.ApplicationPerson
				}).then(resJson => {
					if (!resJson.Data) {
						// 说明该报销人姓名存在人员档案中 允许保存和提交
						this.$errorToast(type == 0 ? '报销人不在人员档案中，无法保存' : '报销人不在人员档案中，无法提交')
						return
					}
					// 最终提交
					this.SubmitRequest(type)

				})
				console.log('保存了', type, this.entity)
			},

			// 最终提交
			SubmitRequest(type) {

				// 点击 1.保存草稿  2  提交
				var that = this
				this.$refs.form.validate().then(res => {
					// this.resetFields()
					this.loading = true

					// 单独处理主表李的到达城市id参数
					// 出发城市
					// 如果有值 说明已经更改过出发城市  查找赋值
					if (this.entity.newDepartureCity) {
						this.entity.DepartureCity = this.entity.newDepartureCity
					}
					// 最终附件参数字段格式化
					if (this.tripDetailData !== null && this.tripDetailData.length > 0) {
						this.tripDetailData.forEach(item => {
							// 判断是否有reimburse_Travel_Business_SubsidyDTOs字段 只有详情有  添加的字段是detail  格式化处理
							if (item.detailData) {
								// 说明是新加进来的行程数据
								item['reimburse_Travel_Business_SubsidyDTOs'] = item.detailData
							}

							item.reimburse_Travel_Business_SubsidyDTOs.forEach(item => {
								if (!item.Id) {
									// 只有再新增的条件下处理
									// 出发城市到达城市 业务性质参数格式化处理
									item.DepartureCity = item.newDepartureCity
									item.ArrivalCityId = item.newArrivalCityId
									item.ExpenseType = item.newExpenseType
								}

								// 单独附件格式参数处理
								let Upload = []
								let reimburse_Files = []
								if (item.reimburse_Files && item.reimburse_Files.length > 0) {
									item.reimburse_Files.forEach(v => {
										// 如果是新上传的 直接放到Upload里
										if (v.fileEntity.id && !v.invoiceId) {
											delete v.invoiceId
											Upload.push(v)
										}
										// /如果是详情过来的直接push详情
										if (v.fileEntity.Id) {
											reimburse_Files.push(v.fileEntity)
										} else {
											// 否则是新上传的直接取linkurlpush
											let obj = {
												FilePath: v.fileEntity.linkUrl
											}
											reimburse_Files.push(obj)
										}

									})
									item.reimburse_Files = reimburse_Files
									item.Upload = Upload
								}
							})

						})
					}

					let newEntity = JSON.parse(JSON.stringify(this.entity))
					// newEntity['CreatorId'] = this.UserInfo.UserInfo.CreatorId
					// 提交 1  草稿  0
					newEntity['Satus'] = type
					console.log(
						'差旅进入修改--------------------------------------------------------------------------------开始i提交了',
						newEntity, this.tripDetailData)

					uni.showLoading({
						title: '加载中'
					})

					Reimburse_Travel_Business_MainSaveData(newEntity)
						.then(resJson => {
							if (resJson.Success) {
								that.$sucessToast(type == 0 ? '保存成功' : '提交成功')
								setTimeout(function() {
									that.loading = false
									uni.navigateBack()
									uni.hideLoading()

								}, 2500)
							} else {
								that.$errorToast(resJson.Msg);
								setTimeout(function() {
									that.loading = false
									uni.navigateBack()
									uni.hideLoading()
								}, 2500)
							}

						});

				}).catch(err => {
					uni.hideLoading()
					that.loading = false
				})


			}



		}
	}
</script>

<style lang="less" scoped>
	// 覆盖uni-section 的样式uni-section
	::v-deep.uni-section {
		.uni-section-header {
			padding: 24rpx 0 !important;
		}
	}

	/* 设置 label 的样式 */
	::v-deep.uni-forms-item {
		padding-right: 40rpx !important;
		// margin-bottom: 15rpx !important;

		/* 例如，设置 label 的宽度和对齐方式 */
		.uni-forms-item__label {
			display: flex !important;
			justify-content: flex-end !important;
		}
	}

	.container {
		.scrollBox {

			margin-bottom: 130rpx;
			/* #ifdef H5 */
			height: calc(100vh - 360px);
			/* #endif */
			/* #ifdef APP */
			height: calc(100vh - 220px);
			/* #endif */

			.detail {
				width: 100%;
				margin: 0 auto;
				box-shadow: 3px 4px 16px 0px #6b6b6a;
				margin-top: 40rpx;
				margin-bottom: 10px;
				background-color: #ffffff;
				border-radius: 10rpx;
				padding: 20rpx;
			}
		}

		/* 适配底部导航栏 */
		.submitButton {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			height: 150rpx;
			/*暂时发现安卓小屏手机安全区为0 && 不带单位的话padding-bottom会失效，写一个兜底, 并写在最上面；f12发现css样式如果都给height设置样式，会依次往下，用最底下的一个样式，如果最下面的没失效，依次往上查找，所以兜底的写在最上面 */
			height: calc(150rpx + constant(safe-area-inset-bottom));
			/* 直接扩展高度，因为padding-bottom是内边距 */
			height: calc(150rpx + env(safe-area-inset-bottom));
			/* 直接扩展高度 */
			background: #fff;
			box-sizing: border-box;
			padding-bottom: constant(safe-area-inset-bottom);
			/*兼容 iOS<11.2 */
			padding-bottom: env(safe-area-inset-bottom);
			/* 兼容iOS>= 11.2*/
			border-top: 1px solid #e9e9e9;
			padding-left: 15px;
			padding-right: 15px;
		}
	}
</style>